<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-row>
        <el-form-item label="活动类型" prop="type">
          <el-select v-model="queryParams.type" clearable placeholder="活动类型">
            <el-option label="全部" value="" ></el-option>
            <el-option label="社区活动" :value="0"></el-option>
            <el-option label="线上活动" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动标题" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入活动标题"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="只看热门" prop="isHot">
          <el-switch
            v-model="queryParams.isHot"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
        </el-form-item>
      </el-row>

      <el-row v-show="queryParams.type != 1">
        <el-form-item label="所在区域" prop="region1Id">
          <el-select v-model="queryParams.region1Id" clearable
                     @change="handleRegion1Change"
                     placeholder="请选择区域">
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="region1 in regionOptions"
              :key="region1.value"
              :label="region1.label"
              :value="region1.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所在街道" prop="region2Id">
          <el-select v-model="queryParams.region2Id" clearable
                     @change="handleRegion2Change"
                     placeholder="请选择街道">
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="region2 in region2List"
              :key="region2.value"
              :label="region2.label"
              :value="region2.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所在社区" prop="region3Id">
          <el-select v-model="queryParams.region3Id" clearable placeholder="请选择社区">
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="region3 in region3List"
              :key="region3.value"
              :label="region3.label"
              :value="region3.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-row>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['health:healthActivity:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['health:healthActivity:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['health:healthActivity:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['health:healthActivity:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 【【 列表展示 】】-->
    <el-table v-loading="loading" :data="healthActivityList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column label="活动id" align="center" prop="id" width="60"/>

      <el-table-column label="活动类型" align="center" prop="type" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.type === 0 ? '社区活动' : '平台活动' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="活动区域" align="center" width="80" prop="regionName">
        <template slot-scope="scope">
          <span>{{ scope.row.regionId === null ? '线上' : scope.row.regionName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="活动地点" align="center" prop="place" width="100"/>
      <el-table-column label="活动日期" align="center" prop="activityDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.activityDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="封面图片" align="center" prop="cover" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.cover" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="活动标题" align="center" prop="title">
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.title" placement="top">
            <div style="
              overflow: hidden;
              display: -webkit-box;
              text-overflow: ellipsis;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
              white-space: normal;"
            >
              {{ scope.row.title }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="活动简介" align="center" prop="brief">
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.brief" placement="top">
            <div style="
              overflow: hidden;
              display: -webkit-box;
              text-overflow: ellipsis;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
              white-space: normal;"
            >
              {{ scope.row.brief }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="热门" align="center"
                       width="50px" prop="isHot">
        <template slot-scope="scope">
          <span>{{ scope.row.isHot === 0 ? '否' : '是' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" width="80px"
                       prop="createBy"/>
      <el-table-column label="创建时间" align="center"
                       width="100px"
                       prop="createTime"/>
      <el-table-column label="操作" align="center"
                       width="120px"
                       class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['health:healthActivity:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['health:healthActivity:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改活动风采管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="活动标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入活动标题"/>
        </el-form-item>

        <el-row>
          <el-col :span="8">
            <el-form-item label="活动类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择" @change="ActivityTypeChange">
                <el-option label="社区活动" :value="0"></el-option>
                <el-option label="平台活动（线上）" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="活动区域" prop="regionId" v-show="form.type === 0">
              <el-cascader
                v-model="form.regionId"
                placeholder="试试搜索区域的名称+"
                :options="regionOptions"
                :props="{ expandTrigger: 'hover' ,emitPath:false}"
                :style="{ 'width':'100%'}"
                filterable
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动地点" prop="place">
              <el-input v-model="form.place" placeholder="请输入活动地点"/>
            </el-form-item>
            <el-form-item label="活动日期" prop="activityDate">
              <el-date-picker clearable
                              v-model="form.activityDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择活动日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="活动简介" prop="brief">
              <el-input v-model="form.brief" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
            <el-form-item label="是否热门" prop="isHot" :style="{ 'margin-bottom':'0px'}">
              <el-switch
                v-model="form.isHot"
                active-color="#13ce66"
                inactive-color="#666666"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="封面图片" prop="cover">
              <image-upload v-model="form.cover"
                            :limit="1"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center">活动详情</el-divider>
        <!-- 富文本编辑器 -->
        <editor v-model="activityDetailDetail"
                :min-height="120"
        />

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listHealthActivity,
  getHealthActivity,
  delHealthActivity,
  addHealthActivity,
  updateHealthActivity
} from "@/api/health/healthActivity";
import {getHealthRegionTree, listHealthRegion} from "@/api/health/healthRegion";

export default {
  name: "HealthActivity",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedActivityDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 活动风采管理表格数据
      healthActivityList: [],
      // 活动介绍表格数据
      activityDetailDetail: '',
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: '',  // 空串是全部，0是社区，1是线上
        region1Id: '',
        region2Id: '',
        region3Id: '',
        title: '',
        isHot: 0,
      },
      // 表单参数
      form: {
        isHot: 0,
      },
      // 表单校验
      rules: {},
      //区域选项
      regionOptions: [],
      //区域列表（一级）
      regionList: [],
      //区域类别（二级）
      region2List: [],
      //区域类别（三级）
      region3List: [],
    };
  },
  created() {
    this.getRegionOptions();
    this.getRegionList();
    //顺序不能颠倒
    this.getList();
    //初始化一级、二级区域
    this.handleRegion1Change();
    this.handleRegion2Change();
  },
  methods: {
    /** 查询活动风采管理列表 */
    getList() {
      this.loading = true;
      listHealthActivity(this.queryParams).then(response => {
        this.healthActivityList = response.rows;
        this.total = response.total;
        this.loading = false;
        //处理数据格式，添加regionName
        this.healthActivityList.forEach(act => {
          for (const region of this.regionList) {
            if (act.regionId === region.id) {
              act.regionName = region.name;
              break;
            }
          }
        })
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        regionId: null,
        place: null,
        activityDate: null,
        cover: null,
        title: null,
        brief: null,
        isHot: 0,
        createBy: null,
        createTime: null,
        activityDetail: {}
      };
      this.resetForm("form");
      this.activityDetailDetail = ''
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加活动风采";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getHealthActivity(id).then(response => {
        this.form = response.data;
        console.log(this.form)
        this.activityDetailDetail = this.form.activityDetail.detail || '没有内容';
        this.open = true;
        this.title = "修改活动风采";
      });
    },
    /** 提交按钮 */
    submitForm() {
      //处理数据格式:添加详情
      this.form.activityDetail = {
        detail: this.activityDetailDetail
      }
      // this.form.activityDetail.detail =  this.activityDetailDetail

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateHealthActivity(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHealthActivity(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
      //重置表单
      this.reset();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除活动风采：编号为"' + ids + '"的数据？').then(function () {
        return delHealthActivity(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 活动介绍序号 */
    rowActivityDetailIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('health/healthActivity/export', {
        ...this.queryParams
      }, `healthActivity_${new Date().getTime()}.xlsx`)
    },
    getRegionList() {
      listHealthRegion().then(resp => {
        this.regionList = resp.data
      })
    },
    getRegionOptions() {
      getHealthRegionTree().then(resp => {
        // 区域tree针对 element的cascade组件进行格式调整
        //name---> label
        //id---> value
        // 最后一级，不要有空 children
        this.regionOptions = resp.data.map(region => {
          return this.mapTree(region)
        });

      })
    },
    mapTree(tr) {
      const haveChildren = Array.isArray(tr.children) && tr.children.length > 0;
      let node = {
        //分别将我们查询出来的值做出改变他的key
        label: tr.name,
        value: tr.id,
        // data: {...tr},
        //判断它是否存在子集，若果存在就进行再次进行遍历操作，知道不存在子集便对其他的元素进行操作
        // children: haveChildren ? tr.children.map(child => this.mapTree(child)) : []
      }
      // console.log(node.value, '----', node.label)
      //[改进；最后一级，不要有空 children]
      // 判断它是否存在子集，若果存在就进行再次进行遍历操作，知道不存在子集便对其他的元素进行操作
      if (haveChildren) {
        node.children = tr.children.map(child => this.mapTree(child))
      }
      return node;
    },
    //创建、修改活动时，活动类型改变
    ActivityTypeChange(newType) {
      this.form.regionId = null
    },
    //一级区域改变，联动修改二级区域
    handleRegion1Change(r1Id) {
      if (r1Id == null || r1Id == '') {
        //给二级区域下拉中，填充全部的“二级区域”
        this.region2List = this.regionList.filter(item => {
          return item.level == 2
        })
        //重置二级区域
        this.region2List.map(item => {
          item.label = item.name;
          item.value = item.id
        })
        //选中二级“全部”
        this.queryParams.region2Id = ''
        //重置三级区域
        this.region3List.map(item => {
          item.label = item.name;
          item.value = item.id
        })
        //选中三级“全部”
        this.queryParams.region3Id = ''
      } else {
        let currentRegion1 = this.regionOptions.find((item) => {
          return item.value === r1Id;
        })
        this.region2List = currentRegion1.children;
      }

    },
    //二级区域改变，联动修改三级区域
    handleRegion2Change(r2Id) {
      if (r2Id == null || r2Id == '') {
        this.region3List = this.regionList.filter(item => {
          return item.level == 3
        })
        this.region3List.map(item => {
          item.label = item.name;
          item.value = item.id
        })
        //选中三级“全部”
        this.queryParams.region3Id = ''
      } else {
        let currentRegion2 = this.region2List.find((item) => {
          return item.value === r2Id;
        })
        this.region3List = currentRegion2.children;
      }

    }
  }
};
</script>
